#!/usr/bin/env python

import unittest
import os
from rawdb import RawDB, ShallowCopy, RawDBInvalidId

class RawDB_Test( unittest.TestCase ):
    def setUp( self ):
        self.db = RawDB()
    # setUp()

    def testSet( self ):
        self.db.set( 1, 2 )
        self.db.set( 2, 4 )
        self.db.write( 3, 6 ) # write is an alias to set
    # testSet()


    def testSetGet( self ):
        v = 123
        self.db.set( "test1", v )
        self.assertEqual( self.db.get( "test1" ), v )
        self.assertEqual( self.db.read( "test1" ), v ) # read is an alias
    # testSetGet()


    def testClear( self ):
        self.db.set( "bla", "ble" )
        self.assertNotEqual( len( self.db.list_ids() ), 0 )
        self.db.clear()
        self.assertEqual( len( self.db.list_ids() ), 0 )
    # testClear()


    def testUpdate( self ):
        d1 = { "a": 1, "b": 2 }
        d2 = { "a": "a", "b": "b" }
        self.db.update( d1 )
        for k, v in d1.iteritems():
            self.assertEqual( self.db.get( k ), v )

        self.db.update( d2 )
        for k, v in d2.iteritems():
            self.assertEqual( self.db.get( k ), v )
    # testUpdate()


    def testRestore( self ):
        self.db.clear()
        d1 = { "a": 1, "b": 2, "c": 3 }
        self.db.update( d1 )
        f = os.tmpfile()
        self.db.save( f )
        self.db.clear()
        f.flush()
        f.seek( 0 )
        self.db.load( f )
        for k, v in d1.iteritems():
            self.assertEqual( self.db.get( k ), v )
    # testRestore()


    def testInvalidId( self ):
        self.db.clear()
        self.assertRaises( RawDBInvalidId, self.db.get, 1 )
    # testInvalidKey()
# RawDB_Test


class ShallowCopy_Test( unittest.TestCase ):
    def setUp( self ):
        self.db = RawDB()

        self.d = { "a": 1, "b": 2 }

        self.db.update( self.d )
        
        self.shallow = ShallowCopy( self.db )
    # setUp()


    def testGet( self ):
        for k, v in self.d.iteritems():
            self.assertEqual( self.shallow.get( k ), v )
    # testGet()


    def testSetGet( self ):
        self.shallow.set( "a", 123 )
        self.shallow.set( "c", 3 )

        self.assertEqual( self.shallow.get( "a" ), 123 )
        self.assertEqual( self.shallow.get( "c" ), 3 )

        # assert db wasn't affected
        self.assertEqual( self.db.get( "a" ), self.d[ "a" ] )
    # testSetGet()


    def testCommit( self ):
        self.shallow.set( "a", 123 )
        self.shallow.set( "c", 3 )

        self.shallow.commit()

        # assert db is updated
        self.assertEqual( self.db.get( "a" ), 123 )
        self.assertEqual( self.db.get( "b" ), self.d[ "b" ] )
        self.assertEqual( self.db.get( "c" ), 3 )
    # testCommit()

    def testInvalidId( self ):
        self.db.clear()
        self.shallow.clear()
        self.assertRaises( RawDBInvalidId, self.shallow.get, 1 )
    # testInvalidKey()
# ShallowCopy_Test()


if __name__ == "__main__":
    unittest.main()
# endif
